package library.and.xps.com.step.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.jude.utils.JUtils;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;
import library.and.xps.com.step.view.activity.PersonalChallengeDetailActivity;

public class PushReceiver extends BroadcastReceiver {
    public static final String TAG = "PushReceiver";

    //在此处解析收到的自定义消息
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.d(TAG, "onReceive - " + intent.getAction());

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            //收到自定义消息
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {     //自定义消息可以发送json数据

            System.out.println("收到了自定义消息。消息内容是：" + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            // 自定义消息不会展示在通知栏，完全要开发者写代码去处理
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            System.out.println("收到了通知");
            // 在这里可以做些统计，或者做些其他工作(通知栏被点击)
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            System.out.println("用户点击打开了通知");

            String alert = intent.getStringExtra(JPushInterface.EXTRA_EXTRA);
            Logger.d(alert);
            try {
                JSONObject json = new JSONObject(alert);
                String pkid = json.getString("pkid");
                int pk = json.getInt("pk");
                if(pk==1){
                    openChallengerDetail(context,Integer.valueOf(pkid));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String title = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            JUtils.Log("Received RegId:", title);
        } else {
            Log.d(TAG, "Unhandled intent - " + intent.getAction());
        }
    }

    void openChallengerDetail(Context context, int value){
        Intent i = new Intent(context, PersonalChallengeDetailActivity.class);
        i.putExtra("pkid", value);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }

}
